using System;
using System.Windows.Forms;
using Comteck.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPrinting;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraTreeList;

namespace Comteck.Winforms {
  /// <summary>
  /// Dev扩展方法
  /// </summary>
  public static partial  class DevExtensions {

    #region private methods

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <returns></returns>
    private static string GetControlCaption(object control) {
      var caption = string.Empty;

      if (control is GridControl gridControl) {
        caption = gridControl.MainView.ViewCaption;

        if (caption.IsNullOrEmpty()) {
          caption = gridControl.FindForm()?.Text;
        }
      } else if (control is BaseView baseView) {
        caption = baseView.ViewCaption;

        if (caption.IsNullOrEmpty()) {
          caption = baseView.GridControl.FindForm()?.Text;
        }
      } else if (control is TreeList treeList) {
        caption = treeList.Caption;

        if (caption.IsNullOrEmpty()) {
          caption = treeList.FindForm()?.Text;
        }
      } else if (control is PivotGridControl pivot) {
        if (caption.IsNullOrEmpty()) {
          caption = pivot.FindForm()?.Text;
        }
      }

      return caption;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToXls(object control, string filePath, string sheetName) {
      var options = new XlsExportOptions(TextExportMode.Value, true);

      if (sheetName.IsNotNullOrEmpty()) {
        options.SheetName = sheetName;
      }

      if (control is GridControl gridControl) {
        gridControl.ExportToXls(filePath, options);
      } else if (control is BaseView baseView) {
        baseView.ExportToXls(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToXls(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToXls(filePath, options);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToXlsx(object control, string filePath, string sheetName) {
      var options = new XlsxExportOptions(TextExportMode.Value, true);

      if (sheetName.IsNotNullOrEmpty()) {
        options.SheetName = sheetName;
      }

      if (control is GridControl gridControl) {
        gridControl.ExportToXlsx(filePath, options);
      } else if (control is BaseView baseView) {
        baseView.ExportToXlsx(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToXlsx(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToXlsx(filePath, options);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToPdf(object control, string filePath) {
      var options = new PdfExportOptions() {
        //Compressed = true,
        ConvertImagesToJpeg = true,
      };

      if (control is GridControl gridControl) {
        gridControl.ExportToPdf(filePath);
      } else if (control is BaseView baseView) {
        baseView.ExportToPdf(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToPdf(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToPdf(filePath, options);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToHtml(object control, string filePath) {
      var options = new HtmlExportOptions();

      if (control is GridControl gridControl) {
        gridControl.ExportToHtml(filePath, options);
      } else if (control is BaseView baseView) {
        baseView.ExportToHtml(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToHtml(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToHtml(filePath, options);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToText(object control, string filePath) {
      var options = new TextExportOptions();

      if (control is GridControl gridControl) {
        gridControl.ExportToText(filePath, options);
      } else if (control is BaseView baseView) {
        baseView.ExportToText(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToText(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToText(filePath, options);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToMht(object control, string filePath) {
      var options = new MhtExportOptions();

      if (control is GridControl gridControl) {
        gridControl.ExportToMht(filePath, options);
      } else if (control is BaseView baseView) {
        baseView.ExportToMht(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToMht(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToMht(filePath, options);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToRtf(object control, string filePath) {
      if (control is GridControl gridControl) {
        gridControl.ExportToRtf(filePath);
      } else if (control is BaseView baseView) {
        baseView.ExportToRtf(filePath);
      } else if (control is TreeList treeList) {
        treeList.ExportToRtf(filePath);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToRtf(filePath);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="control"></param>
    /// <param name="filePath"></param>
    private static void ExportToCsv(object control, string filePath) {
      var options = new CsvExportOptions();

      if (control is GridControl gridControl) {
        gridControl.ExportToCsv(filePath, options);
      } else if (control is BaseView baseView) {
        baseView.ExportToCsv(filePath, options);
      } else if (control is TreeList treeList) {
        treeList.ExportToCsv(filePath, options);
      } else if (control is PivotGridControl pivot) {
        pivot.ExportToCsv(filePath, options);
      }
    }

    /// <summary>
    /// GridView导出到各种格式的文件
    /// <para>建议将OptonsPrint的AutoWidth设置为false</para>
    /// </summary>
    /// <param name="gridView">GridView</param>
    /// <param name="exportType">导出类型</param>
    /// <param name="options">导出的样式</param>
    /// <param name="saveDialog">对话框</param>
    /// <param name="control"></param>
    private static void ExportControl(object control, ExportTarget exportType = ExportTarget.Xlsx,
      string fileName = null, string sheetName = null) {

      // nodata
      if (control == null) {
        return;
      }

      #region SaveFileDialog

      // 初始化对话框
      var saveDialog = new SaveFileDialog();
      saveDialog.Title = "导出文件";
      saveDialog.FileName = string.IsNullOrWhiteSpace(fileName) ? GetControlCaption(control) : fileName;

      switch (exportType) {
        case ExportTarget.Xls:
          saveDialog.Filter = "Excel文件(*.xls)|*.xls";
          break;
        case ExportTarget.Xlsx:
          saveDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
          break;
        case ExportTarget.Csv:
          saveDialog.Filter = "CSV文件(*.csv)|*.csv";
          break;
        case ExportTarget.Pdf:
          saveDialog.Filter = "PDF文件(*.pdf)|*.pdf";
          break;
        case ExportTarget.Html:
          saveDialog.Filter = "HTML文件(*.html)|*.html";
          break;
        case ExportTarget.Text:
          saveDialog.Filter = "文本文件(*.txt)|*.txt";
          break;
        case ExportTarget.Mht:
          saveDialog.Filter = "MHT文件(*.mht)|*.mht";
          break;
        case ExportTarget.Rtf:
          saveDialog.Filter = "RTF文件(*.rtf)|*.rtf";
          break;
        //case EnumExportFileType.IMG:
        //  saveDialog.Filter = "图像文件(*.JPEG)|*.JPEG | 图像文件(*.JPG)|*.JPG | 图像文件(*.PNG)| *.PNG";
        //  break;
        default:
          break;
      }

      // 打开对话框
      var dialogResult = saveDialog.ShowDialog();

      // 取消
      if (dialogResult == DialogResult.Cancel) {
        return;
      }

      // 没有选择文件
      if (string.IsNullOrWhiteSpace(saveDialog.FileName)) {
        XtraMessageBox.Show("请输入导出文件的名称");
        return;
      }

      #endregion

      #region Export

      // 鼠标样式
      Cursor.Current = Cursors.WaitCursor;

      //PageByPageExportOptionsBase options

      // 按照不同导出类型
      switch (exportType) {
        case ExportTarget.Xls:
          ExportToXls(control, saveDialog.FileName, sheetName);
          break;
        case ExportTarget.Xlsx:
          ExportToXlsx(control, saveDialog.FileName, sheetName);
          break;
        case ExportTarget.Pdf:
          ExportToPdf(control, saveDialog.FileName);
          break;
        case ExportTarget.Html:
          ExportToHtml(control, saveDialog.FileName);
          break;
        case ExportTarget.Text:
          ExportToText(control, saveDialog.FileName);
          break;
        case ExportTarget.Mht:
          ExportToText(control, saveDialog.FileName);
          break;
        case ExportTarget.Rtf:
          ExportToRtf(control, saveDialog.FileName);
          break;
        case ExportTarget.Csv:
          ExportToCsv(control, saveDialog.FileName);
          break;
        default:
          break;
      }

      Cursor.Current = Cursors.Default;

      #endregion

      #region 打开文件

      var dialog = XtraMessageBox.Show("文件保存成功！{0}您现在是否要打开该文件？".FormatWith(Environment.NewLine),
        "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

      if (dialog == DialogResult.No) {
        return;
      }

      try {
        var process = new System.Diagnostics.Process();
        process.StartInfo.FileName = saveDialog.FileName;
        process.StartInfo.Verb = "Open";
        process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
        process.Start();
      } catch {
        XtraMessageBox.Show("打开失败，请检查是否已安装相应的软件！");
      }

      #endregion
    }

    #endregion

    #region public methods

    /// <summary>
    /// GridView导出到各种格式的文件
    /// <para>建议将OptonsPrint的AutoWidth设置为false</para>
    /// </summary>
    /// <param name="control">GridView</param>
    /// <param name="exportType">导出类型</param>
    /// <param name="fileName">导出的样式</param>
    public static void ExportDialog(this GridControl control, ExportTarget exportType = ExportTarget.Xlsx, string fileName = null, string sheetName = null) {
      ExportControl(control, exportType, fileName, sheetName);
    }

    /// <summary>
    /// GridView导出到各种格式的文件
    /// <para>建议将OptonsPrint的AutoWidth设置为false</para>
    /// </summary>
    /// <param name="control">GridView</param>
    /// <param name="exportType">导出类型</param>
    /// <param name="fileName">导出的样式</param>
    public static void ExportDialog(this BaseView control, ExportTarget exportType = ExportTarget.Xlsx, string fileName = null, string sheetName = null) {
      ExportControl(control, exportType, fileName, sheetName);
    }

    /// <summary>
    /// GridView导出到各种格式的文件
    /// <para>建议将OptonsPrint的AutoWidth设置为false</para>
    /// </summary>
    /// <param name="control">GridView</param>
    /// <param name="exportType">导出类型</param>
    /// <param name="fileName">导出的样式</param>
    public static void ExportDialog(this TreeList control, ExportTarget exportType = ExportTarget.Xlsx, string fileName = null, string sheetName = null) {
      ExportControl(control, exportType, fileName, sheetName);
    }

    /// <summary>
    /// GridView导出到各种格式的文件
    /// <para>建议将OptonsPrint的AutoWidth设置为false</para>
    /// </summary>
    /// <param name="control">GridView</param>
    /// <param name="exportType">导出类型</param>
    /// <param name="fileName">导出的样式</param>
    public static void ExportDialog(this PivotGridControl control, ExportTarget exportType = ExportTarget.Xlsx, string fileName = null, string sheetName = null) {
      ExportControl(control, exportType, fileName, sheetName);
    }

    /// <summary>
    /// 绑定导出控件的事件
    /// </summary>
    /// <param name="item">导出的主按钮</param>
    /// <param name="control">待导出的控件</param>
    public static void SetExportEvent(this BarSubItem item, GridControl control) {
      foreach (LinkPersistInfo link in item.LinksPersistInfo) {
        // 非按钮
        if (link.Item == null || (link.Item is BarButtonItem) == false) {
          continue;
        }

        var tag = link.Item.Tag;

        if (tag == null) {
          continue;
        }

        var exportType = EnumHelper.CastInt2Enum<ExportTarget>(tag);

        link.Item.ItemClick += (x, y) => {
          control.ExportDialog(exportType);
        };
      }
    }

    #endregion
    #region 等待窗口操作 add by alex

    /// <summary>
    /// 打开等待窗口
    /// </summary>
    /// <param name="form">当前调用窗体</param>
    /// <param name="description">提示内容</param>
    /// <param name="caption">标题，默认值："温馨提示"</param>
    public static void ShowWaitForm(this Form form, string description, string caption = "温馨提示") {
      SplashScreenManager.ShowForm(form, typeof(FrmWaitForm), true, true, false);
      SplashScreenManager.Default.SetWaitFormCaption(caption);
      SplashScreenManager.Default.SetWaitFormDescription(description);
    }
    /// <summary>
    /// 关闭等待窗口
    /// </summary>
    /// <param name="form">当前调用窗体</param>
    /// <param name="closingDelay">窗口关闭延时时间，单位：ms. </param>
    /// <param name="content">提示内容</param>
    /// <param name="caption">标题，默认值："温馨提示"</param>
    public static void CloseWaitForm(this Form form, int closingDelay, string content, string caption = "温馨提示") {
      SplashScreenManager.Default?.SetWaitFormCaption(caption);
      SplashScreenManager.Default?.SetWaitFormDescription(content);
      SplashScreenManager.CloseForm(false, closingDelay, form);
    }
    #endregion
  }
}
